﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Infrastructure.CustomException;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.EFCore.Extensions;
using QMERP.Infrastructure.Extensions;

namespace QMERP.Application.Services
{
    public class WarehouseService : IWarehouseService
    {
        private readonly IMapper _mapper;
        private readonly QMERPDbContext _db;
        public WarehouseService(IMapper mapper, QMERPDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }
        /// <summary>
        /// 获取仓库列表基础数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<WarehouseResponse>> GetBasicWarehouses()
        {
            var list = await _db.Warehouse.ToListAsync();
            return _mapper.Map<List<WarehouseResponse>>(list);
        }
        /// <summary>
        /// 仓库窗体
        /// </summary>
        /// <returns></returns>
        public async Task<PageResponse<WarehouseResponse>> Query(PageRequest<WarehouseRequest> request)
        {
            var response = new PageResponse<WarehouseResponse>();

            var query = Where(request);

            var list = await query.Paging(request.PageIndex, request.PageSize).ToListAsync();
            var warehouseResponse = _mapper.Map<List<WarehouseResponse>>(list);
            response.TotalCount = await query.CountAsync();
            response.PageIndex = request.PageIndex;
            response.PageSize = request.PageSize;
            response.List = warehouseResponse;
            return response;
        }
        /// <summary>
        /// 获取id的仓库详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<WarehouseResponse> Detail(long id)
        {
            var model = await _db.Warehouse.FindByIdAsync(id);
            return _mapper.Map<WarehouseResponse>(model);
        }
        /// <summary>
        /// 仓库保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(WarehouseSaveRequest request)
        {
            if (await _db.Warehouse.AnyAsync(x => x.Code.ToLower() == request.Code && x.Id != request.Id))
                throw new ApiException("仓库代码已存在!");
            if (await _db.Warehouse.AnyAsync(x => x.Name.ToLower() == request.Name && x.Id != request.Id ))
                throw new ApiException("仓库名称已存在!");
            if (request.Id == null)
            {
                Warehouse model = _mapper.Map<Warehouse>(request);
                await _db.Warehouse.AddAsync(model);
            }
            else
            {
                Warehouse? model = await _db.Warehouse.FindByIdAsync(request.Id.Value);
                if (model == null)
                    throw new ApiException("仓库不存在!");
                model.Code = request.Code;
                model.Name = request.Name;
                model.Address = request.Address;
                model.ManageManName = request.ManageManName;
                model.Telephone = request.Telephone;
                model.Attribute = request.Attribute;
                model.Remark = request.Remark;
            }
            await _db.SaveChangesAsync();
        }

        private IQueryable<Warehouse> Where(PageRequest<WarehouseRequest> request)
        {
            IQueryable<Warehouse> query = _db.Warehouse;
            if (!request.Query.Code.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Code.Contains(request.Query.Code!));
            }
            if (!request.Query.Name.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Name.Contains(request.Query.Name!));
            }
            return query.OrderByDescending(x => x.CreatedOn);
        }
    }
}
